﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using CID.Domain.Development;
using CID.Domain.Users;
using CID.Web.Models.Users;

namespace CID.Web.Models.Development
{
    public class ReleaseViewModel : BaseDescribedViewModel<IRelease>
    {
        #region Properties
        public ReleaseStatus Status { get; set; }

        [HiddenInput(DisplayValue = false)]
        [Required(ErrorMessage = "You must provide a Responsible")]
        public int? ResponsibleId { get; set; }
        public string Responsible { get; set; }

        public IEnumerable<VersionViewModel> Versions { get; set; }
        #endregion

        #region Edtion helper members
        private IEnumerable<User> availableUsers;

        #region Users
        public void SetAvailableUsers(IEnumerable<User> availableUsers)
        {
            this.availableUsers = availableUsers;
        }

        public IEnumerable<UserViewModel> AvailableUsers
        {
            get { return availableUsers.ToList().Select(x => new UserViewModel(x)); }
        }
        #endregion

        #endregion

        public ReleaseViewModel() : base() { }
        public ReleaseViewModel(IRelease model) : base(model)
        {
            Status = model.Status;

            if (model.Responsible != null)
            {
                ResponsibleId = model.Responsible.Id;
                Responsible = model.Responsible.Name;
            }
            Versions = model.Versions.Select(x => new VersionViewModel(x));
        }

        public override void UpdateModel(IRelease model)
        {
            base.UpdateModel(model);
            model.Responsible = availableUsers.Single(x => x.Id == ResponsibleId);
            UpdateStatus(model);
        }

        public void UpdateStatus(IRelease model)
        {
            if (model.Status != Status)
            {
                switch (Status)
                {
                    case ReleaseStatus.Planned:
                        break;
                    case ReleaseStatus.Active:
                        model.SetActive();
                        break;
                    case ReleaseStatus.Released:
                        model.SetReleased();
                        break;
                    case ReleaseStatus.Obsolete:
                        model.SetObsolete();
                        break;
                }
            }
        }

    }
}
